package practise.mulitThreads.ConcurrentInPractice;

import java.util.Date;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by richard on 6/13/14.
 */
public class StatisticThreadPool extends ThreadPoolExecutor {
    ThreadLocal<Long> threadTime = new ThreadLocal(){
        @Override
        protected Object initialValue() {
            return new Date().getTime();
        }
    };

    AtomicLong executeDuration = new AtomicLong(0);

    public StatisticThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public StatisticThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    public StatisticThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    }

    public StatisticThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        System.out.println("Thread " + t.getName() + " is to start at " + new Date(threadTime.get()));
        super.beforeExecute(t, r);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        System.out.println("Thread " + r.toString() + " is finished using " + (executeDuration.addAndGet(new Date().getTime()- threadTime.get())));
        super.afterExecute(r, t);
    }

    @Override
    protected void terminated() {
        System.out.println("Executor total running " + executeDuration.get());
        super.terminated();
    }
}
